﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkAssetManager.Entity;
using System.Management;
using log4net; 
namespace NetworkAssetManager.WMI
{
    class UserGroups
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(UserGroups));

        private static ManagementScope _scope = null; 
        public static string GetDetails(string domainName, string parent)
        {
            string users = string.Empty;
            string qry = string.Format("select * from Win32_GroupUser where GroupComponent=\"Win32_Group.Domain='{0}',Name='{1}'\"", domainName, parent);
            ObjectQuery query = new ObjectQuery(qry);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(_scope, query);
            try
            {
                foreach (ManagementObject mObject in searcher.Get())
                {
                    ManagementPath path = new ManagementPath(mObject["PartComponent"].ToString());
                    String[] names = path.RelativePath.Split('=');
                    users += (path.RelativePath.Substring(path.ClassName.Length + 8).Replace(",Name=", "\\").Replace("\"", "")) + ", ";
                }
            }
            catch (Exception)
            {
                users = "";
            }

            return users;
        }

        private static EntUserGroups FillDetails(ManagementBaseObject obj)
        {
            EntUserGroups objEntUserGroups = new EntUserGroups();
            try
            {
                objEntUserGroups.Caption = WMIUtil.ToString(obj["Caption"]);
            }
            catch (Exception)
            {
                objEntUserGroups.Caption = "";
            }

            try
            {
                objEntUserGroups.Description = WMIUtil.ToString(obj["Description"]);
            }
            catch (Exception)
            {
                objEntUserGroups.Description = "";
            }

            try
            {
                objEntUserGroups.Domain = WMIUtil.ToString(obj["domain"]);
            }
            catch (Exception)
            {
                objEntUserGroups.Domain = "";
            }

            try
            {
                objEntUserGroups.InstallDate = WMIUtil.ToDateTime((string)obj["InstallDate"]);
            }
            catch (Exception)
            {
                objEntUserGroups.InstallDate = DateTime.MinValue;
            }

            try
            {
                objEntUserGroups.LocalAccount = (bool)obj["LocalAccount"]; 
            }
            catch (Exception)
            {
                objEntUserGroups.LocalAccount = false;
            }

            try
            {
                objEntUserGroups.Name = WMIUtil.ToString(obj["Name"]);
            }
            catch (Exception)
            {
                objEntUserGroups.Name = "";
            }

            try
            {
                objEntUserGroups.SID = WMIUtil.ToString(obj["SID"]);
            }
            catch (Exception)
            {
                objEntUserGroups.SID = "";
            }

            try
            {
                objEntUserGroups.Status = WMIUtil.ToString(obj["Status"]);
            }
            catch (Exception)
            {
                objEntUserGroups.Status = "";
            }

            try
            {
                objEntUserGroups.Users = GetDetails(objEntUserGroups.Domain, objEntUserGroups.Name);
            }
            catch (Exception)
            {
                objEntUserGroups.Users = "";
            }




                         
            return objEntUserGroups;
        }
        public static List<EntUserGroups>GetUserGroupDetails(ManagementScope scope)
        {
            _scope = scope; 
            _logger.Info("Collecting user groups details for machine " + _scope.Path.Server);

            ObjectQuery query = null;
            ManagementObjectSearcher searcher = null;
            ManagementObjectCollection objects = null;
            List<EntUserGroups> lstUserGroup = new List<EntUserGroups>();

            try
            {
                query = new ObjectQuery("Select * from Win32_Group");
                searcher = new ManagementObjectSearcher(_scope, query);
                objects = searcher.Get();
                lstUserGroup.Capacity = objects.Count;
                foreach (ManagementBaseObject obj in objects)
                {
                    lstUserGroup.Add(FillDetails(obj));
                    obj.Dispose();
                }
            }
            catch (System.Exception e)
            {
                _logger.Error("Exception in user groups collection " + e.Message);
            }
            finally
            {
                searcher.Dispose();
                _scope = null; 

            }
            return lstUserGroup;
        }
    }
}
